package com.yzion.baselib.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.IdRes
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.BusUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.ThreadUtils
import com.weikaiyun.fragmentation.SupportActivity
import com.weikaiyun.fragmentation.SupportFragment
import com.weikaiyun.fragmentation_swipeback.SwipeBackFragment
import com.yzion.baselib.R
import com.yzion.baselib.activity.BaseActivity
import com.yzion.baselib.activity.IBarOption
import com.yzion.baselib.app.IAppProvider
import com.yzion.baselib.dialog.BaseLoadingDialog
import com.yzion.baselib.view.BaseTitleBar
import kotlinx.coroutines.cancel

/**
 * Fragment基类，支持手势侧滑关闭，支持默认标题栏，支持自定义标题栏，支持加载等待弹窗，支持Toast，支持状态栏浸沉
 */
abstract class BaseFragment : SwipeBackFragment(), IBarOption {

    private var contentView: View? = null
    private var rootView: ViewGroup? = null

    private var baseLoadingDialog: BaseLoadingDialog? = null
    private var titleBar: BaseTitleBar? = null
    private var customTitleBar: View? = null

    protected abstract fun setContentView(
        inflater: LayoutInflater,
        savedInstanceState: Bundle?
    ): View

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
//        fragmentAnimator = (requireContext().applicationContext as IAppProvider).createFragmentAnimator()
        rootView = if (isTitleBarFlow()) {
            inflater.inflate(R.layout.by_fragment_flow, container, false) as ViewGroup
        } else {
            inflater.inflate(R.layout.by_fragment, container, false) as ViewGroup
        }
        val contentContainer = findViewById<ViewGroup>(R.id.base_container)
        contentView = setContentView(inflater, savedInstanceState)
        val params = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        contentContainer.addView(contentView, params)
        return if (isSwipeBackEnable()) {
            attachToSwipeBack(rootView)
        } else {
            rootView
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        baseLoadingDialog =
            (requireContext().applicationContext as IAppProvider).createLoadingDialog(requireContext()) as BaseLoadingDialog
        initTitleBar()
        initView()

        BusUtils.register(this)
        initData()

        BusUtils.post("onFragmentCreated")
    }

    private fun initTitleBar() {
        val layout = findViewById<ViewGroup>(R.id.base_toolbar_layout)
        val params = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        customTitleBar = createCustomTitleBar()
        if (customTitleBar != null) {
            layout.addView(customTitleBar, params)
            setStatusBarPadding(layout)
        } else if (isUseDefaultTitleBar()) {
            titleBar = createDefaultTitleBar()
            layout.addView(titleBar, params)
            setStatusBarPadding(layout)
            titleBar?.setBarLayout(layout)
        }
    }

    private fun setStatusBarPadding(layout: ViewGroup) {
        if (activity != null && activity is BaseActivity) {
            //判断父容器是否启用浸沉式
            val isEnableImmersive = (activity as BaseActivity).isEnableImmersive()
            if (isEnableImmersive) { //开启沉浸式才需要留出状态栏的高度
                layout.setPadding(0, BarUtils.getStatusBarHeight(), 0, 0)
            }
        }
    }

    override fun createDefaultTitleBar(): BaseTitleBar {
        return (requireContext().applicationContext as IAppProvider).createTitleBarView(
            requireContext()
        )
    }

    override fun onDestroy() {
        super.onDestroy()
        BusUtils.unregister(this)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        hideLoading()
        hideSoftInput()
        lifecycleScope.cancel()
    }

    fun <T : View?> findViewById(@IdRes id: Int): T {
        checkNotNull(rootView) { "You should call this method after onCreateView!" }
        return rootView!!.findViewById(id)
    }

    fun showLoading(text: String? = null): BaseLoadingDialog? {
        ThreadUtils.runOnUiThread {
            try {
                baseLoadingDialog?.setLoadingTip(text)?.show()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return baseLoadingDialog
    }

    fun hideLoading() {
        ThreadUtils.runOnUiThread {
            try {
                baseLoadingDialog?.dismiss()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    /**
     * 初始化UI
     */
    protected abstract fun initView()

    /**
     * 初始化数据
     */
    abstract fun initData()

    fun onBackPressed() {
        activity?.onBackPressed()
    }

    /**
     * @param isBlack if true, set icons and text color to black.
     * if false, set icons and text color to white.
     */
    fun setStatusBar(isBlack: Boolean) {
        activity?.let { BarUtils.setStatusBarLightMode(it.window, isBlack) }

    }

    /**
     * 标题栏是否浮在内容视图之上，默认是false的
     *
     * @return
     */
    override fun isTitleBarFlow(): Boolean {
        return false
    }


    /**
     * 是否开启侧滑退出
     *
     * @return
     */
    open fun isSwipeBackEnable(): Boolean {
        return false
    }


    /**
     * 注意：如果使用了自定义标题栏（返回不为空），即使isUseDefaultTitleBar设置为true，
     * 自定义标题栏也会覆盖默认标题栏
     *
     * @return
     */
    override fun createCustomTitleBar(): View? {
        return null
    }

    /**
     * 是否使用全局配置的TitleBar视图，默认配置是使用DefaultTitleBar
     *
     * @return
     */
    override fun isUseDefaultTitleBar(): Boolean {
        return false
    }

    /**
     * 返回自定义标题栏视图，非全局自定义，是当前Fragment的自定义标题栏视图
     * @return
     */
    override fun getCustomTitleBar(): View? {
        return customTitleBar
    }

    /**
     * 返回标题栏视图，默认的配置是使用DefaultTitleBar，如果需要自定义请参见DefaultTitleBar注释
     * @return
     */
    override fun <TitleBar : View> getTitleBar(): TitleBar? {
        if (titleBar != null) {
            @Suppress("UNCHECKED_CAST")
            return titleBar as TitleBar
        }
        return null
    }

    /**
     * 启动跟父Fragment同级的Fragment
     *
     * @param fragment
     */
    fun parentStart(fragment: SupportFragment) {
        if (parentFragment != null && parentFragment is SupportFragment) {
            (parentFragment as SupportFragment).start(fragment)
        } else {
            start(fragment)
        }
    }

    /**
     * 启动跟父activity同级的Fragment
     *
     * @param fragment
     */
    fun rootStart(fragment: SupportFragment) {
        if (activity != null && activity is SupportActivity) {
            (activity as SupportActivity).start(fragment)
        }
    }

    /**
     * 隐藏键盘
     */
    override fun hideSoftInput() {
        runCatching {
            if (KeyboardUtils.isSoftInputVisible(requireActivity())) KeyboardUtils.hideSoftInput(
                requireActivity()
            )
        }
    }

    fun isDestroy(): Boolean {
        return isRemoving || isDetached || activity == null
    }


}